package cn.feng.mybatis.base.a_3.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.feng.mybatis.base.a_2.test.entity.User;
import cn.feng.mybatis.base.a_3.dao.UserDao;

/**
 * 4.2原始dao开发方法（程序员需要写dao接口和dao实现类）
 * 
 * 
 * 4.2.1思路 程序员需要写dao接口和dao实现类。
 * 需要向dao实现类中注入SqlSessionFactory，在方法体内通过SqlSessionFactory创建SqlSession
 */
public class UserDaoImpl implements UserDao {

	private SqlSessionFactory sqlSessionFactory;

	// 需要向dao实现类中注入SqlSessionFactory
	// 这里通过构造方法注入
	public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
		super();

		this.sqlSessionFactory = sqlSessionFactory;
	}

	@Override
	public User getUserById(int id) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		User user = sqlSession.selectOne("test.getUserById", id);
		// 释放资源
		sqlSession.close();
		return user;
	}

	@Override
	public List<User> getUserByName(String name) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		List<User> list = sqlSession.selectList("test.getUserByName", name);
		// 释放资源
		sqlSession.close();
		return list;

	}

	@Override
	public void insertUser(User user) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.insert("test.insertUser", user);
		// 提交事务
		sqlSession.commit();

		// 释放资源
		sqlSession.close();
	}

	@Override
	public void deleteUser(int id) throws Exception {
		SqlSession sqlSession = sqlSessionFactory.openSession();
		sqlSession.delete("test.deleteUser", id);
		// 提交事务
		sqlSession.commit();
		// 释放资源
		sqlSession.close();
	}

}
